
interface CSVItem {
    No: number;
    Ticker: string;
    Company: string;
    Sector: string;
    Industry: string;
    Country: string;
    MarketCap: number;
    PE: number;
    Price: number;
    Change: number;
    Volume: number;
}

const FinvizToken = 'badafdcf-0c37-4f48-a476-54b471df6c2c';

export async function screener_export(params: string) {
    const fetch_url = `/elite_finviz/export.ashx?v=111${params}&auth=${FinvizToken}`;

    const csv = (await (await fetch(fetch_url)).text()).split('\n');
    csv.splice(0, 1);
    csv.pop();

    const list = [] as CSVItem[];

    csv.forEach((value, index) => {
        const item = value.split(',');
        list.push({
            No: parseInt(item[0]),
            Ticker: item[1].replaceAll('"', ''),
            Company: item[2].replaceAll('"', ''),
            Sector: item[3].replaceAll('"', ''),
            Industry: item[4].replaceAll('"', ''),
            Country: item[5].replaceAll('"', ''),
            MarketCap: parseInt(item[6]),
            PE: parseInt(item[7]),
            Price: parseInt(item[8]),
            Change: parseInt(item[9]),
            Volume: parseInt(item[10]),
        })
    })

    return list;
}

type Timeframe = 'i1' | 'i2' | 'i3' | 'i5' | 'i10' | 'i15' | 'i30' | 'h' | 'h2' | 'h4' | 'd' | 'w' | 'm';

export function create_get_chart_task(
    ticker: string,
    timeframe: Timeframe = 'd',
    premarket: boolean = false,
    aftermarket: boolean = false,
    candlestick_count: number = 1,
): () => Promise<void> {
    const _premarket = premarket === true ? 'true' : 'false';
    const _aftermarket = aftermarket === true ? 'true' : 'false';
    const fetch_url = new URL('https://api.finviz.com/api_finviz/api/quote.ashx?instrument=stock');
    fetch_url.searchParams.set('ticker', ticker);
    fetch_url.searchParams.set('timeframe', timeframe);
    fetch_url.searchParams.set('premarket', _premarket);
    fetch_url.searchParams.set('aftermarket', _aftermarket);
    fetch_url.searchParams.set('barsCount', candlestick_count.toString());

    return () => {
        return new Promise((resolve) => {
            chart(fetch_url.pathname + fetch_url.search).then(data => {
                resolve(data)
            })
        })
    }
}

async function chart(fetch_url: string) {
    try {
        const response = await fetch(fetch_url);
        const object = await response.json();
        return object;
    } catch (err) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve(chart(fetch_url))
            }, 1000)
        })
    }
}




